<?php

namespace Beerus\Modules\PackageOrder\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\package\OrderLogisticsLog;
use Biz\model\package\PackageLogistics;
use Biz\service\trade\ShopCourier as sShopCourier;
use Doraemon\pockets\excel\DownExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;

class LogisticsController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $requestData = $request->all();
        $condition = self::getCondition($requestData);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list = self::format($where);

        //查询物流公司列表
        $courierList = sShopCourier::getCourierFileList();
        $courier = [];
        foreach ($courierList as $item) {
            if (empty($item['trackingmore_code'])) {
                continue;
            }
            $key = $item['courier_name'];
            $courier[$key] = $item['courier_name'];
        }
        unset($where['LIMIT']);
        $total = PackageLogistics::count($where);
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $courier, $where) {
                $grid->paginate($gridModel->getPerPage());
                $grid->tools(function (Grid\Tools $tools) use ($where) {
                    $downUrl = '/admin/packageOrder/logistics/downExcel?condition=' . base64_encode(json_encode($where));
                    $tools->append("<a href='{$downUrl}' class='btn button-success'><i class='fa fa-file-excel-o'></i>>批量导出</a>");
                });
                $grid->filter(function ($filter) use ($courier) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) use ($courier) {
                        $filter->equal('order_logistics_no', '物流单号')->placeholder('物流单号');
                        $filter->equal('express_company', '物流公司')->select($courier);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('status',
                            '物流状态')->select(PackageLogistics::STATUS_MAP);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableActions();
                $grid->column('id', '主键ID');
                $grid->column('order_logistics_no', '物流单号');
                $grid->column('express_company', '物流公司');
                $grid->column('tracking', '物流最新进展')->modal('物流流转详情', function ($trackInfo) {
                    $trackInfos = $trackInfo->track_info["logistics_info"];
                    $data = [];
                    if ($trackInfos) {
                        foreach ($trackInfos as $item) {
                            $data[] = [
                                'Details' => $item['accept_station'],
                                'Date' => $item['accept_time'],
                            ];
                        }
                    }
                    return new Table(['状态描述', '日期'], $data);
                });
                $grid->column('shipping_fee', '运费');
                $grid->column('goods', '包含商品');
                $grid->column('edittime', '最新物流信息的更新时间');
                $grid->column('status', '物流状态');
                $grid->column('addtime', '物流创建时间');
            }
        );
        $tab = new Tab();
        $tab->add('新人礼包-物流记录', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('新人礼包-物流记录')
            ->description(' ')
            ->breadcrumb(['text' => '新人礼包-物流记录', 'url' => '/packageOrder/logistics']);
    }

    /**
     * @param $request
     * @return array
     */
    private static function getCondition($request): array
    {
        $condition['ORDER'] = ['id' => 'DESC'];
        if (isset($request['order_logistics_no']) && !empty($request['order_logistics_no'])) {
            $condition['order_logistics_no'] = $request['order_logistics_no'];
        }
        if (isset($request['express_company']) && !empty($request['express_company'])) {
            $condition['express_company'] = $request['express_company'];
        }
        if (isset($request['status']) && !empty($request['status'])) {
            $condition['status'] = $request['status'];
        }

        return $condition;

    }

    private static function format($where) {
        $packageLogistics = PackageLogistics::selectByWhere($where);
        if (empty($packageLogistics)) {
            return [];
        }
        $orderLogistics = array_column($packageLogistics,  'order_logistics_no');
        $logisticsLog = OrderLogisticsLog::selectInfo(['order_logistics_no' => $orderLogistics]);
        foreach ($packageLogistics as &$package) {
            if ($package['goods_id'] == 1) {
                $package['goods'] = '包裹1';
            } elseif ($package['goods_id'] == 2) {
                $package['goods'] = '包裹1';
            } elseif ($package['goods_id'] == 3) {
                $package['goods'] = '包裹3';
            }
            $package['track_info'] = $logisticsLog[$package['order_logistics_no']];
            $package['status'] = PackageLogistics::STATUS_MAP[$package['status']];
            $package['addtime'] = date('Y-m-d H:i:s', $package['addtime']);
            $package['edittime'] = date('Y-m-d H:i:s', $package['edittime']);
            $package['tracking'] = $logisticsLog[$package['order_logistics_no']]['logistics_info'][0]['accept_station'] ?? '';
        }
        return $packageLogistics;
    }

    public function downExcel(Request $request)
    {
        $params = $request->all();
        $where = json_decode(base64_decode($params['condition']), true);
        $downExcel = new DownExcel();
        $title = '批量导出';
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $packageLogistics = PackageLogistics::selectByWhere($where);
        if (empty($packageLogistics)) {
            return [];
        }
        $exportList = [];
        foreach ($packageLogistics as $k => $item) {
            if ($item['goods_id'] == 1) {
                $goods = '包裹1';
            } elseif ($item['goods_id'] == 2) {
                $goods = '包裹1';
            } elseif ($item['goods_id'] == 3) {
                $goods = '包裹3';
            }
            $exportList[$k]['order_no'] = $item['order_no'];
            $exportList[$k]['order_logistics_no'] = $item['order_logistics_no'].' ';
            $exportList[$k]['express_company'] = $item['express_company'];
            $exportList[$k]['shipping_fee'] = $item['shipping_fee'];
            $exportList[$k]['edittime'] = $item['edittime'] ? date('Y-m-d H:i:s', $item['edittime']) : '';
            $exportList[$k]['goods_id'] = $goods;
            $exportList[$k]['status'] = PackageLogistics::STATUS_MAP[$item['status']];
            $exportList[$k]['addtime'] = $item['addtime'] ? date('Y-m-d H:i:s', $item['addtime']) : '';

        }

        $head = [
            '订单ID', '物流单号', '物流公司', '实际运费', '物流信息更新时间', '包含商品', '物流状态', '物流创建时间'
        ];
        $downExcel->create($exportList, $head);
        return back();
    }
}